package com.share.all.rest;

import com.share.all.model.Response;
import com.share.all.service.FileStorageService;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 来源：https://www.javaguides.net/2020/04/spring-boot-file-upload-download-rest-api-example.html
 * @author caifan
 * created 2024/1/23 15:09
 */
@RestController
@RequestMapping("/file")
public class FileUploadRest {

    @Autowired
    private FileStorageService fileStorageService;

    @PostMapping("/upload")
    public Response uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        String fileName = fileStorageService.storeFile(file);
        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath().path("/downloadFile")
                .path(fileName)
                .toUriString();

        return new Response(fileName, fileDownloadUri, file.getContentType(), file.getSize());
    }

    @PostMapping("/uploads")
    public List<Response> uploadFiles(@RequestParam("files") MultipartFile[] files) throws IOException {
        List<Response> responses = new ArrayList<>(files.length);
        for (MultipartFile file : files) {
            responses.add(uploadFile(file));
        }
        return responses;
    }

    @PostMapping("/download/{fileName:.+}")
    private ResponseEntity downloadFile(@PathVariable String fileName, HttpServletRequest request) throws IOException, ServletException {
        Resource resource = fileStorageService.loadFileAsResource(fileName);
        String contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        if (StringUtils.isEmpty(contentType)) {
            contentType = "application/octet-stream";
        }
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

}
